package com.rocketmq.demo.base.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @ProjectName: rocketmq-demo
 * @Package: com.rocketmq.demo.base.consumer
 * @ClassName: Consumer
 * @Author: mac
 * @Description: 消息消费者
 * @Date: 2021/4/1 1:14 下午
 * @Version: 1.0
 */
public class Consumer {

    public static void main(String[] args) {

        //1.实例化消息消费者,制定消费者组
        DefaultMQPushConsumer consumer =  new DefaultMQPushConsumer("group1");

        //2.指定nameServer地址
        consumer.setNamesrvAddr("192.168.31.67:9876;192.168.31.126:9876;192.168.31.209:9876");

        //3.设置消费模式:负载均衡|广播模式
        consumer.setMessageModel(MessageModel.BROADCASTING);

        //4.设置回调函数处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            //接收消息类容
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg: list){
                    System.out.println("consumerThread:"+Thread.currentThread().getName());
                    System.out.println("consumerMes:"+ new String(msg.getBody()));
                    System.out.println("mes:"+ msg.toString());
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        try {
            consumer.subscribe("springboot-mq","*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
